# render_split.py (c) 2012 Blender PO!
#
# ***** BEGIN GPL LICENSE BLOCK *****
#
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will 
#
#be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
# GNU General Public License for more details.
#
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ***** END GPL LICENCE BLOCK *****

bl_info = {
    'name': 'Render Split',
    'author': 'BlenderPo Community',
    'version': (0,1),
    "blender": (2, 6, 0),
    "api": 41098,
    'location': 'PROPERTIES -> RENDER',
    'description': 'Renderiza separando los diferentes canales de una capa',
    'warning': 'Este addon fue concebido con la induccion de pizza y alcohol', # used for warning icon and text in addons panel
    'category': 'Render'}

import bpy, os
#, random, time
#from pdb import set_trace

#mod_data = [tuple(["actions"]*3), tuple(["armatures"]*3), 
#                 tuple(["cameras"]*3), tuple(["curves"]*3),
#                 tuple(["fonts"]*3), tuple(["grease_pencil"]*3),
#                 tuple(["groups"]*3), tuple(["images"]*3),
#                 tuple(["lamps"]*3), tuple(["lattices"]*3),
#                 tuple(["libraries"]*3), tuple(["materials"]*3),
#                 tuple(["meshes"]*3), tuple(["metaballs"]*3),
#                 tuple(["node_groups"]*3), tuple(["objects"]*3),
#                 tuple(["sounds"]*3), tuple(["texts"]*3), 
#                 tuple(["textures"]*3),]

#if bpy.app.version[1] >= 60:
#   mod_data.append( tuple(["speakers"]*3), )


class RenderLayerSplit(bpy.types.Operator):
    '''Renderiza de los canales de las capas de render'''
    bl_idname="ba.render_split_layers"
    bl_label="Render Split Layers"
    
    def execute(self, context):
        #target = context.scene.active_layer
        #target_coll = eval("bpy.data." + target)
        
        #num_deleted = len([x for x in target_coll if x.users==0])
        #num_kept = len([x for x in target_coll if x.users==1])
        
        #for item in target_coll:
            #if item.users == 0:
                #target_coll.remove(item)
        escenas = bpy.data.scenes.keys()
        layeractivo = bpy.context.scene.render.layers.active
        escenaactiva = bpy.context.scene
        salida = bpy.context.scene.render.filepath
        counta = 0
        frames = 0


        print (escenas)
        print (escenaactiva, layeractivo)
        print (salida)

        print(layeractivo.use_pass_ambient_occlusion)
        print(layeractivo.use_pass_color)
        print(layeractivo.use_pass_combined)
        print(layeractivo.use_pass_diffuse)
        print(layeractivo.use_pass_environment)
        print(layeractivo.use_pass_indirect)
        print(layeractivo.use_pass_material_index)
        print(layeractivo.use_pass_mist)
        print(layeractivo.use_pass_normal)
        print(layeractivo.use_pass_object_index)
        print(layeractivo.use_pass_reflection)
        print(layeractivo.use_pass_refraction)
        print(layeractivo.use_pass_shadow)
        print(layeractivo.use_pass_specular)
        print(layeractivo.use_pass_uv)
        print(layeractivo.use_pass_vector)
        print(layeractivo.use_pass_z)
        print(layeractivo.use_pass_emit)
     
        #for item in escenas:
        #    os.system("mkdir -p /home/iniciativa/render_split/" + item)

        os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name)
        
        if layeractivo.use_pass_combined == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/combined")
            counta = counta + 1
            
        if layeractivo.use_pass_ambient_occlusion == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/ambient_occlusion")
            counta = counta + 1

        if layeractivo.use_pass_color == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/color")
            counta = counta + 1

        if layeractivo.use_pass_diffuse == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/diffuse")
            counta = counta + 1

        if layeractivo.use_pass_environment == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/environment")
            counta = counta + 1

        if layeractivo.use_pass_material_index == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/material_index")
            counta = counta + 1

        if layeractivo.use_pass_indirect == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/indirect")
            counta = counta + 1

        if layeractivo.use_pass_mist == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/mist")
            counta = counta + 1

        if layeractivo.use_pass_normal == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/normal")
            counta = counta + 1

        if layeractivo.use_pass_object_index == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/object_index")
            counta = counta + 1

        if layeractivo.use_pass_reflection == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/reflection")
            counta = counta + 1

        if layeractivo.use_pass_refraction == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/refraction")
            counta = counta + 1

        if layeractivo.use_pass_shadow == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/shadow")    
            counta = counta + 1

        if layeractivo.use_pass_specular == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/specular")
            counta = counta + 1

        if layeractivo.use_pass_uv == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/uv")
            counta = counta + 1

        if layeractivo.use_pass_specular == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/specular")
            counta = counta + 1

        if layeractivo.use_pass_vector == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/vector")
            counta = counta + 1

        if layeractivo.use_pass_z == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/z")
            counta = counta + 1

        if layeractivo.use_pass_emit == 1:
            os.system("mkdir -p " + salida + escenaactiva.name + "/" + layeractivo.name + "/emit")
            counta = counta + 1

#        msg = "Procesados %d cuadros. %s capas y %d Canales" % (num_deleted, target,
#                                                            num_kept)
#        self.report( { 'INFO' }, msg  )

        msg = "Procesados %d cuadros. en %s , en la capa %s y %d Canales" % (frames, escenaactiva.name, layeractivo.name, counta)
        self.report( { 'INFO' }, msg  )

        #print num_deleted[]

        return {'FINISHED'}
    
class RenderSplitPanel( bpy.types.Panel ):
    '''Main Panel for Render Slipt script'''
    bl_label = "Render Split"
    bl_space_type = "PROPERTIES"
    bl_region_type = "WINDOW"
    bl_context = "render"
    
    def draw( self, context ):
        scn = context.scene
        layout = self.layout
        new_col = self.layout.column
        
#        new_col().column().prop(scn, "mod_list")
        new_col().column().operator("ba.render_split_layers")
    

def register():
    
    
 #   bpy.types.Scene.mod_list = bpy.props.EnumProperty(name="Target", 
 #                          items=mod_data, 
 #                          description="Module choice made for orphan deletion")

    bpy.utils.register_class(RenderLayerSplit)
    bpy.utils.register_class(RenderSplitPanel)
    

def unregister():
    bpy.utils.unregister_class(RenderSplitPanel)
    bpy.utils.unregister_class(RenderLayerSplit)


if __name__ == "__main__":
    register()




#import os       bpy.context.scene.layers[0] = True     bpy.ops.render.render(layer='layername', scene='Scene')

# bpy.context.scene.render.filepath


        # CAMBIO SCENE
        #bpy.context.window.screen.scene=SCENE

#import bge

#print("lee archivo")

#path = bge.logic.expandPath("//saves") # or os.path.join(os.getcwd(), "saves")
#path = os.path.join(os.getcwd(), "Escritorio/saves")
#file = "map.save"

#with open(os.path.join(path, file)) as f:
#    print(f.read())
    #print("-----")
    
#memFile = open('/proc/meminfo')
#print(memFile.read())
#for line in memFile.readlines():
#    if line.startswith("MemTotal"):
#        memStr = line.split()
#        memTotal = memStr[1]
#        memFile.close()
#        print("Memory: " + memTotal + "kB")

#import os
#from bge import logic
#from bge import events

#cont = logic.getCurrentController()
#obj = cont.owner

##fecha = os.system("date")
#Fecha = os.popen("dropbox status | head -n1")
#laFecha = Fecha.read()
#hoyEs = '"Dropbox Status: ' + laFecha + '"'
##print(hoyEs)


#prop = cont.actuators['Property']
##print(prop.value)
#prop.value = hoyEs
#cont.activate(prop)